package com.maidshop.fp.service.impl;

import com.maidshop.common.utils.RandomCharUtils;
import com.maidshop.fp.domain.FileUpload;
import com.maidshop.fp.mapper.FileMapper;
import com.maidshop.fp.service.FileService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * 文件上传实现类
 */
@Service
public class FileServiceImpl {

    @Value("${fileUpload.path}")
    private String path;

    @Resource
    private FileMapper fileMapper;

    public FileUpload saveFile(MultipartFile file) {
        return saveFile2Local(file);
    }

    private FileUpload saveFile2Local(MultipartFile file) {
        // 保存文件到本地
        // 随机生成文件名
        String fileName = UUID.randomUUID().toString() + "." + file.getOriginalFilename().split("\\.")[1];
        // 获取今日日期
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String today = LocalDate.now().format(formatter);
        // 文件保存路径
        String savePath = today + "/" + fileName;
        // 判断文件夹是否存在，不存在则创建
        Path path = Paths.get(this.path + today);
        if (!path.toFile().exists()) {
            path.toFile().mkdirs();
        }
        // 往数据库插入数据
        String s = RandomCharUtils.generateRandomString();
        fileMapper.insertNewData(s, savePath);
        // 保存文件
        try {
            byte[] bytes = file.getBytes();
            Path filePath = path.resolve(fileName);
            FileOutputStream outputStream = new FileOutputStream(filePath.toFile());
            outputStream.write(bytes);
            outputStream.close();
            return FileUpload.builder()
                    .fileName(fileName)
                    .uploadTime(LocalDate.now().toString())
                    .fileId(s)
                    .relativePath(today + "/" + fileName)
                    .build();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
